package metro.general;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import metro.general.util.Commons;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Main extends BaseActivity {
	protected static final double DISTANCE_LIMIT = 5000;
	private LocationManager mLocationManager;
	private JSONArray mMetroStation = null;
	private double mMinDistance = Integer.MAX_VALUE;
	private JSONObject mMetroMinDistance;

	// private AdView adView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		setupLocationManager();
		ImageButton accediPdf = (ImageButton) findViewById(R.id.accedi_pdf);
		accediPdf.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Intent intent = new Intent(Main.this, TabView.class);
				startActivity(intent);

			}
		});

		LinearLayout linearLayoutButton = (LinearLayout) findViewById(R.id.navigatore);
		linearLayoutButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				performedNavigator();
			}
		});

		ImageButton imageButton = (ImageButton) findViewById(R.id.imageDistance);
		imageButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				performedNavigator();
			}

		});

		ImageButton accediMaps = (ImageButton) findViewById(R.id.accedi_maps);
		accediMaps.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				Intent intent = new Intent(Main.this, Maps.class);
				intent.putExtra("latitude", mLocation.getLatitude());
				intent.putExtra("longitude", mLocation.getLongitude());
				startActivity(intent);

			}
		});

	}

	private void setupLocationManager() {

		mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
				&& !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.warning)
					.setMessage(R.string.localization_disable).setPositiveButton("Ok", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							initGPS();
							showTime.run();
						}

					}).show();
		} else if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.warning)
					.setMessage(R.string.localization_gps_disable).setPositiveButton("Ok", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							initGPS();
							showTime.run();
						}

					}).show();
		} else {
			initGPS();
			showTime.run();
		}
	}

	protected void parseXml() {
		InputStream is = getResources().openRawResource(R.raw.metro);
		Writer writer = new StringWriter();
		char[] buffer = new char[1024];
		try {
			Reader reader = null;
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			int n;
			while ((n = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, n);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			mMetroStation = new JSONArray(writer.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Commons.getInstance().setMetroStation(mMetroStation);

		try {
			calculateDistance();
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	private void calculateDistance() throws JSONException {
		double distance;

		for (int i = 0; i < mMetroStation.length(); i++) {
			JSONObject o = null;
			try {
				o = (JSONObject) mMetroStation.get(i);
			} catch (JSONException e1) {
				e1.printStackTrace();
			}

			try {
				// TEST
				// Location locationb = new Location("");
				// locationb.setLatitude(45.460371);
				// locationb.setLongitude(9.182854);
				// END

				Location locationA = new Location("");
				locationA.setLatitude(Double.parseDouble(o.getString("latitude")));
				locationA.setLongitude(Double.parseDouble(o.getString("longitude")));
				distance = locationA.distanceTo(mLocation);

				if (mMinDistance > distance) {
					mMinDistance = distance;
					mMetroMinDistance = o;
				}

			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}

		((TextView) findViewById(R.id.textDistance)).setText(getString(R.string.nearest_station_label) + " "
				+ mMetroMinDistance.getString("metro") + ", " + getString(R.string.distance) + " " + (int) (mMinDistance) + " "
				+ getString(R.string.meters));
		hideProgressAsync();
	}

	private void performedNavigator() {
		try {
			String uri = "http://maps.google.com/maps?saddr=" + mLocation.getLatitude() + "," + mLocation.getLongitude() + "&daddr="
					+ Double.parseDouble(mMetroMinDistance.getString("latitude")) + ","
					+ Double.parseDouble(mMetroMinDistance.getString("longitude"));
			if (mMinDistance < DISTANCE_LIMIT) {
				uri += "&dirflg=w";
			}
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
			startActivity(intent);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// Intent intent = new Intent(Main.this, MapRoute.class);
		// startActivity(intent);

	}
}